<template>
    <el-dialog v-model="dialogVisible" title="新增消费记录" width="380px" :close-on-click-modal="false" @close="closeDialog">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="110px" class="pt10 pr15">
            <el-form-item label="积分变动类型" prop="change_type" required>
                <el-radio-group v-model="ruleForm.change_type">
                    <el-radio :value="1">增加</el-radio>
                    <el-radio :value="2">减少</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="积分数量" prop="change_point">
                <GInputNumber
                    id="change_point"
                    type="nonzero"
                    v-model="ruleForm.change_point"
                    placeholder="请输入积分数量"
                    clearable
                    @input="inputPointNum"
                />
            </el-form-item>
            <el-form-item label="确认积分数量" prop="reprice_point">
                <GInputNumber
                    id="reprice_point"
                    type="nonzero"
                    v-model="ruleForm.reprice_point"
                    placeholder="请输入确认积分数量"
                    clearable
                />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
                <el-input id="remark" v-model="ruleForm.remark" placeholder="请输入备注" clearable/>
            </el-form-item>
            <el-form-item label="会员积分增加情况" class="mb10">
                <ul>
                    <li v-for="row in addPointData" :key="row.label" class="f-c text-nowrap">
                        <span class="w70">{{ row.name }}</span>
                        <span class="w60">{{ row.count }}次</span>
                        <span class="w120">共计 {{ row.point }} 分</span>
                    </li>
                </ul>
            </el-form-item>
        </el-form>

        <template #footer>
            <el-button @click="cancelDialog">取消</el-button>
            <el-button type="primary" :loading="subLoading" :disabled="subLoading" @click="submitForm(ruleFormRef)">确认</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
    import { reactive, ref, nextTick, watch } from "vue";
    import { ElMessage } from "element-plus";
    import { getRestfulMallPointsStats } from "@/assets/api";

    const props = defineProps({
        modelValue: {
            type: Boolean,
            default: false,
        },
        memberId: {
            type: Number,
            default: 0,
        },
    })

    const ruleForm = reactive<ObjValueAny>({
        member_id: props.memberId,
        change_type: 1,
        type: 2,
        change_point: '',
        reprice_point: '',
        remark: '',
    });

    let dialogVisible = ref<boolean>(false);// 显示弹窗
    let subStatus: boolean = false;
    let subLoading = ref<boolean>(false);
    const ruleFormRef = ref();

    const inputPointNum = () => {
        nextTick(() => {
            ruleFormRef.value.validateField('reprice_point', () => {
            })
        })
    }

    const formStringEmptyRule = (message: string) => {
        return (rule: ObjValueAny, value: string, callback: Function) => {
            if (subStatus && !value) {
                return callback(new Error(message));
            }
            callback()
        }
    }
    const validatorRepointNum = (rule: ObjValueAny, value: string, callback: Function) => {
        if (subStatus) {
            if (!value) {
                return callback(new Error('请输入积分数量'))
            }
            if (+ruleForm.change_point !== +value) {
                return callback(new Error('积分数量不一致，请确认积分数量'))
            }
        }
        callback()
    }
    const rules = reactive<ObjValueAny>({
        change_point: [{ required: true, validator: formStringEmptyRule('请输入积分数量'), trigger: 'change' }],
        reprice_point: [{ required: true, validator: validatorRepointNum, trigger: 'change' }],
    })

    const submitForm = (formEl: any) => {
        subStatus = true;
        if (!formEl) return;
        formEl.validate((valid: boolean, fields: ObjValueAny) => {
            if (valid) {
                console.log('submit!');
                onSave();
            } else {
                console.log('error submit!', fields);
            }
        });
    }

    const addPointData = reactive<ObjValueAny[]>([
        { name: '今天', count: 0, point: 0 },
        { name: '7天内', count: 0, point: 0 },
        { name: '30天内', count: 0, point: 0 },
    ]);
    const getPointsStats = () => {
        getRestfulMallPointsStats({
            origin: 1,
            point_type: 1,
            member_id: props.memberId,
        }).then((resp: ObjValueAny) => {
            if (resp.code === 200) {
                const { data } = resp;
                addPointData[0].count = data.day_count;
                addPointData[0].point = data.day_total;

                addPointData[1].count = data.week_count;
                addPointData[1].point = data.week_total;

                addPointData[2].count = data.month_count;
                addPointData[2].point = data.month_total;
            } else {
                ElMessage.error(resp.msg);
            }
        })
    }
    // 监听 弹窗显示隐藏
    watch(() => props.modelValue, (newVal: boolean) => {
        if (newVal) {
            getPointsStats();
        }
        dialogVisible.value = newVal;
        subLoading.value = false;
        subStatus = false;
    })
    const emit = defineEmits(['update:modelValue', 'add']);
    // 关闭弹窗
    const closeDialog = () => {
        cancelDialog();
        emit('update:modelValue', dialogVisible.value)
    }
    // 关闭弹窗
    const cancelDialog = () => {
        resetRuleForm(ruleFormRef.value);
        dialogVisible.value = false;
    }
    const resetRuleForm = (formEl: any) => {
        if (!formEl) return;
        formEl.resetFields();
    }
    const onSave = () => {
        subLoading.value = true;
        const data: ObjValueAny = getRuleFormHandler();
        console.info(data);
        // postRestfulMallOrder(data).then(() => {})
    }
    const getRuleFormHandler = () => {
        const data: ObjValueAny = { ...ruleForm };
        delete data.reprice_point;
        return data;
    }
</script>